from flask import Blueprint, request, jsonify, send_file
from werkzeug.utils import secure_filename
import os
import logging
from utils.error_handler import APIError
from typing import Optional

def create_api_blueprint(session_manager, image_processor, gemini_client, rate_limiter):
    """创建API蓝图"""
    
    api = Blueprint('api', __name__)
    
    def check_rate_limit():
        """检查速率限制"""
        allowed, remaining = rate_limiter.is_allowed()
        if not allowed:
            reset_time = rate_limiter.get_reset_time()
            raise APIError(
                message=f"请求频率过高，请在 {reset_time} 后重试",
                status_code=429,
                error_code="RATE_LIMIT_EXCEEDED"
            )
        return remaining
    
    @api.route('/docs')
    def api_docs():
        """API文档"""
        return jsonify({
            'title': '图生图转接API文档',
            'version': '1.0.0',
            'description': '基于Gemini 2.0 Flash的图片生成和编辑API',
            'endpoints': {
                'POST /generate': {
                    'description': '生成或编辑图片',
                    'parameters': {
                        'prompt': '文本提示（必需）',
                        'image': '输入图片（可选，base64或文件上传）',
                        'session_id': '会话ID（可选，用于多轮对话）'
                    },
                    'response': {
                        'success': '是否成功',
                        'data': {
                            'image': '生成的图片（base64）',
                            'text': 'AI响应文本',
                            'session_id': '会话ID'
                        },
                        'message': '响应消息'
                    }
                },
                'POST /session': {
                    'description': '创建新会话',
                    'response': {
                        'success': True,
                        'data': {'session_id': '会话ID'}
                    }
                },
                'GET /session/{session_id}': {
                    'description': '获取会话信息',
                    'response': {
                        'success': True,
                        'data': '会话数据'
                    }
                },
                'DELETE /session/{session_id}': {
                    'description': '删除会话',
                    'response': {
                        'success': True,
                        'message': '会话已删除'
                    }
                }
            },
            'examples': {
                'text_to_image': {
                    'request': {
                        'prompt': '生成一只可爱的小猫咪'
                    }
                },
                'image_editing': {
                    'request': {
                        'prompt': '将这只猫咪的背景改为花园',
                        'image': '...'
                    }
                }
            }
        })
    
    @api.route('/generate', methods=['POST'])
    def generate_image():
        """生成或编辑图片"""
        try:
            # 检查速率限制
            remaining_requests = check_rate_limit()
            
            # 获取请求数据
            data = request.get_json() if request.is_json else {}
            
            # 获取参数
            prompt = data.get('prompt') or request.form.get('prompt')
            session_id = data.get('session_id') or request.form.get('session_id')
            
            if not prompt:
                raise APIError("缺少必需参数: prompt", 400, "MISSING_PROMPT")
            
            # 处理会话
            if session_id:
                session_data = session_manager.get_session(session_id)
                if not session_data:
                    raise APIError("会话不存在或已过期", 404, "SESSION_NOT_FOUND")
                conversation_history = session_data.get('conversation_history', [])
            else:
                session_id = session_manager.create_session()
                conversation_history = []
            
            # 处理图片输入
            input_image_path = None
            input_image_base64 = None
            
            # 检查base64图片
            if 'image' in data and data['image']:
                input_image_base64 = data['image']
                # 验证并保存图片
                temp_path, error = image_processor.process_base64_image(input_image_base64)
                if error:
                    raise APIError(f"图片处理失败: {error}", 400, "IMAGE_PROCESSING_ERROR")
                input_image_path = temp_path
            
            # 检查文件上传
            elif 'image' in request.files:
                file = request.files['image']
                temp_path, error = image_processor.process_uploaded_file(file)
                if error:
                    raise APIError(f"文件上传失败: {error}", 400, "FILE_UPLOAD_ERROR")
                input_image_path = temp_path
                # 转换为base64用于存储
                input_image_base64 = image_processor.image_to_base64(temp_path)
            
            # 调用Gemini API
            if input_image_path:
                # 图片编辑
                output_image_base64, ai_response, error = gemini_client.edit_image_with_base64(
                    input_image_base64, prompt, conversation_history
                )
            else:
                # 文本生成图片
                output_image_base64, ai_response, error = gemini_client.generate_image_from_text(
                    prompt, conversation_history
                )
            
            # 清理临时文件
            if input_image_path:
                image_processor.cleanup_file(input_image_path)
            
            if error:
                raise APIError(f"图片生成失败: {error}", 502, "GENERATION_ERROR")
            
            # 更新会话
            session_manager.add_to_conversation(
                session_id, prompt, ai_response or "图片已生成",
                input_image_base64, output_image_base64
            )
            
            # 构建响应
            response_data = {
                'success': True,
                'data': {
                    'image': output_image_base64,
                    'text': ai_response,
                    'session_id': session_id
                },
                'message': '图片生成成功'
            }
            
            # 添加速率限制头
            response = jsonify(response_data)
            response.headers['X-RateLimit-Remaining'] = str(remaining_requests - 1)
            response.headers['X-RateLimit-Reset'] = str(rate_limiter.get_reset_time())
            
            return response
            
        except APIError as e:
            return jsonify(e.to_dict()), e.status_code
        except Exception as e:
            logging.error(f"生成图片时发生错误: {e}")
            return jsonify({
                'success': False,
                'error': 'INTERNAL_ERROR',
                'message': '服务器内部错误',
                'status_code': 500
            }), 500

    @api.route('/session', methods=['POST'])
    def create_session():
        """创建新会话"""
        try:
            session_id = session_manager.create_session()
            return jsonify({
                'success': True,
                'data': {
                    'session_id': session_id
                },
                'message': '会话创建成功'
            })
        except Exception as e:
            logging.error(f"创建会话时发生错误: {e}")
            return jsonify({
                'success': False,
                'error': 'INTERNAL_ERROR',
                'message': '创建会话失败',
                'status_code': 500
            }), 500

    @api.route('/session/<session_id>', methods=['GET'])
    def get_session(session_id):
        """获取会话信息"""
        try:
            session_data = session_manager.get_session(session_id)
            if not session_data:
                raise APIError("会话不存在或已过期", 404, "SESSION_NOT_FOUND")

            # 移除敏感信息
            safe_session_data = {
                'session_id': session_data['session_id'],
                'created_at': session_data['created_at'],
                'last_activity': session_data['last_activity'],
                'conversation_count': len(session_data.get('conversation_history', []))
            }

            return jsonify({
                'success': True,
                'data': safe_session_data,
                'message': '获取会话信息成功'
            })
        except APIError as e:
            return jsonify(e.to_dict()), e.status_code
        except Exception as e:
            logging.error(f"获取会话时发生错误: {e}")
            return jsonify({
                'success': False,
                'error': 'INTERNAL_ERROR',
                'message': '获取会话失败',
                'status_code': 500
            }), 500

    @api.route('/session/<session_id>/history', methods=['GET'])
    def get_conversation_history(session_id):
        """获取对话历史"""
        try:
            limit = request.args.get('limit', 10, type=int)
            history = session_manager.get_conversation_history(session_id, limit)

            if history is None:
                raise APIError("会话不存在或已过期", 404, "SESSION_NOT_FOUND")

            # 处理历史记录，移除base64图片数据以减少响应大小
            safe_history = []
            for entry in history:
                safe_entry = {
                    'timestamp': entry['timestamp'],
                    'user_input': entry['user_input'],
                    'ai_response': entry['ai_response'],
                    'has_input_image': bool(entry.get('input_image')),
                    'has_output_image': bool(entry.get('output_image'))
                }
                safe_history.append(safe_entry)

            return jsonify({
                'success': True,
                'data': {
                    'history': safe_history,
                    'total_count': len(safe_history)
                },
                'message': '获取对话历史成功'
            })
        except APIError as e:
            return jsonify(e.to_dict()), e.status_code
        except Exception as e:
            logging.error(f"获取对话历史时发生错误: {e}")
            return jsonify({
                'success': False,
                'error': 'INTERNAL_ERROR',
                'message': '获取对话历史失败',
                'status_code': 500
            }), 500

    @api.route('/session/<session_id>', methods=['DELETE'])
    def delete_session(session_id):
        """删除会话"""
        try:
            success = session_manager.delete_session(session_id)
            if not success:
                raise APIError("会话不存在", 404, "SESSION_NOT_FOUND")

            return jsonify({
                'success': True,
                'message': '会话删除成功'
            })
        except APIError as e:
            return jsonify(e.to_dict()), e.status_code
        except Exception as e:
            logging.error(f"删除会话时发生错误: {e}")
            return jsonify({
                'success': False,
                'error': 'INTERNAL_ERROR',
                'message': '删除会话失败',
                'status_code': 500
            }), 500

    return api
